package camid.distribution.activeobject;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.concurrent.Future;

public class LocalInvocationHandler implements InvocationHandler {

	private ObjectScheduler scheduler;
	
	public LocalInvocationHandler(ObjectScheduler scheduler) 
	{
		this.scheduler = scheduler;
	}

	@Override
	public Object invoke(Object callee, Method method, Object[] params)
			throws Throwable 
	{
		Future<?> future = scheduler.submitTask(method.getName(), params);
		Object result = null;
		if( Future.class.isAssignableFrom(method.getReturnType()) )
		{
			result = future;
		}
		else
		{
			result = future.get();
			if(result != null && result instanceof Exception)
				throw (Exception)result;
		}
		
		return result;
	}

}
